﻿#include "Video_Convert.h"
#include <QDebug>
extern "C" {
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}

Video_Convert::Video_Convert():
    width_(0)
    ,height_(0)
    ,format_(AV_PIX_FMT_NONE)
    ,sws_Context_(nullptr)
{

}

bool Video_Convert::Open(int32_t in_width, int32_t in_height, AVPixelFormat in_format, int32_t out_width, int32_t out_height, AVPixelFormat out_format)
{
    if(sws_Context_)
    {
        return false;
    }

    if(!sws_Context_)
    {
        sws_Context_ = sws_getContext(in_width,in_height,in_format,
                                     out_width,out_height,out_format,
                                     SWS_BICUBIC,NULL,NULL,NULL);
        width_ = out_width;
        height_ = out_height;
        format_ = out_format;
        return sws_Context_ != nullptr;
    }
    return false;
}

void Video_Convert::Close()
{
    if(sws_Context_)
    {
        sws_freeContext(sws_Context_);
        sws_Context_ = nullptr;
    }
}

int32_t Video_Convert::Convert(AVFramePtr in_frame, AVFramePtr& out_frame)
{
    if(!sws_Context_)
    {
        return -1;
    }
    out_frame = AVFramePtr(av_frame_alloc(), [](AVFrame* p) {av_frame_free(&p);});
    out_frame->width = width_;
    out_frame->height = height_;
    out_frame->format = format_;
    out_frame->pts = in_frame->pts;
    out_frame->pkt_dts = in_frame->pkt_dts;
    out_frame->duration = in_frame->duration;
    out_frame->pkt_duration = in_frame->pkt_duration;
    if(av_frame_get_buffer(out_frame.get(),32) != 0)
    {
        return -1;
    }
    int32_t height_slice = sws_scale(sws_Context_,in_frame->data,in_frame->linesize,0,in_frame->height,out_frame->data,out_frame->linesize);
    if(height_slice < 0)
    {
        return -1;
    }
    return height_slice;
}

Video_Convert::~Video_Convert()
{
    Close();
}
